import React, {
  useState,
  useEffect,
  useMemo,
  useCallback,
  useRef,
} from "react";
import { DragDropContext, Droppable, Draggable } from "@hello-pangea/dnd";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Label } from "@/components/ui/label";
import { ConstructionSchemeAPI } from "@/api/ConstructionScheme";
import {
  Plus,
  Trash2,
  GripVertical,
  Edit3,
  ChevronDown,
  ChevronRight,
  Clock,
  Users,
  Wrench,
  Shield,
  CheckSquare,
  Leaf,
  Truck,
  Package,
  Check,
  Calendar,
  BarChart3,
  Info,
  Calculator,
} from "lucide-react";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";

// 自动调整高度的文本区域组件
const AutoResizingTextarea = ({
  value,
  onChange,
  placeholder,
  rows = 3,
  ...props
}) => {
  const textareaRef = useRef(null);

  useEffect(() => {
    if (textareaRef.current) {
      textareaRef.current.style.height = "auto";
      const scrollHeight = textareaRef.current.scrollHeight;
      const minHeight = rows * 24;
      textareaRef.current.style.height = `${Math.max(scrollHeight, minHeight)}px`;
    }
  }, [value, rows]);

  return (
    <textarea
      ref={textareaRef}
      value={value}
      onChange={onChange}
      placeholder={placeholder}
      rows={rows}
      style={{
        resize: "none",
        overflow: "hidden",
      }}
      {...props}
    />
  );
};

// 工程参数计算组件 - 修复版
const EngineeringCalculator = ({ 
  value, 
  onChange, 
  schemeId,
  disabled,
  minQuantity = 1,
  engineeringParams = [],
  paramsLoading = false
}) => {
  const [isCalcMode, setIsCalcMode] = useState(false);
  const [selectedParam, setSelectedParam] = useState("");
  const [coefficient, setCoefficient] = useState(1);
  const [reserve, setReserve] = useState(0);
  const [calculatedValue, setCalculatedValue] = useState(minQuantity);

  // 修复：处理工程参数值
  const getParamValue = useCallback((param) => {
    // 优先使用 num 字段作为值，如果 num 为 null 则使用 0
    if (param && param.num !== null && param.num !== undefined) {
      return parseFloat(param.num) || 0;
    }
    return 0;
  }, []);

  // 修复：获取选中的参数值
  const getSelectedParamValue = useCallback(() => {
    if (!selectedParam) return 0;
    
    const param = engineeringParams.find(p => 
      String(p.num) === String(selectedParam)
    );
    if (!param) return 0;
    
    return getParamValue(param);
  }, [selectedParam, engineeringParams, getParamValue]);

  // 修复：计算最终值
  const calculateFinalValue = useCallback(() => {
    if (!isCalcMode || !selectedParam) {
      return Math.max(minQuantity, parseInt(value) || minQuantity);
    }
    
    const paramValue = getSelectedParamValue();
    const coeff = parseFloat(coefficient) || 0;
    const res = parseFloat(reserve) || 0;
    
    const calculated = paramValue * coeff + res;
    return Math.max(minQuantity, Math.round(calculated));
  }, [isCalcMode, selectedParam, coefficient, reserve, minQuantity, value, getSelectedParamValue]);

  // 修复：改进同步逻辑
  useEffect(() => {
    const newValue = calculateFinalValue();
    setCalculatedValue(newValue);
    
    // 只有在计算模式下且参数有效时才自动更新
    if (isCalcMode && selectedParam) {
      onChange(newValue);
    }
  }, [calculateFinalValue, isCalcMode, selectedParam, onChange]);

  // 修复：初始化值处理
  useEffect(() => {
    if (value !== undefined && value !== null) {
      const numValue = Math.max(minQuantity, parseInt(value) || minQuantity);
      if (!isCalcMode) {
        setCalculatedValue(numValue);
      }
    }
  }, [value, minQuantity, isCalcMode]);

  // 切换模式
  const toggleMode = () => {
    if (isCalcMode) {
      // 从计算模式切换回简单模式，使用当前计算值
      setIsCalcMode(false);
      onChange(calculatedValue);
    } else {
      // 从简单模式切换到计算模式
      setIsCalcMode(true);
      // 如果有工程参数，默认选择第一个
      if (engineeringParams.length > 0 && !selectedParam) {
        setSelectedParam(engineeringParams[0].num);
      }
    }
  };

  // 清空计算参数
  const clearCalculation = () => {
    setSelectedParam("");
    setCoefficient(1);
    setReserve(0);
    const defaultValue = Math.max(minQuantity, parseInt(value) || minQuantity);
    setCalculatedValue(defaultValue);
    onChange(defaultValue);
  };

  // 获取选中的参数数据
  const selectedParamData = engineeringParams.find(p => p.num === selectedParam);
  const paramValue = getSelectedParamValue();
  const finalValue = calculateFinalValue();

  if (!isCalcMode) {
    // 简单输入模式
    return (
      <div className="flex items-center gap-2">
        <Input
          type="number"
          value={calculatedValue}
          onChange={(e) => {
            const numValue = parseFloat(e.target.value) || 0;
            const finalValue = Math.max(minQuantity, numValue);
            setCalculatedValue(finalValue);
            onChange(finalValue);
          }}
          min={minQuantity}
          step="1"
          className="w-20"
          disabled={disabled}
        />
        <Tooltip>
          <TooltipTrigger asChild>
            <Button
              type="button"
              variant="outline"
              size="sm"
              onClick={toggleMode}
              disabled={disabled || !schemeId || engineeringParams.length === 0}
              className="h-8 px-2"
            >
              <Calculator className="w-3 h-3 mr-1" />
              计算
            </Button>
          </TooltipTrigger>
          <TooltipContent>
            <p>切换到工程计算模式</p>
            {(!schemeId || engineeringParams.length === 0) && (
              <p className="text-xs text-orange-600 mt-1">
                {!schemeId ? '需要方案ID' : '无工程参数可用'}
              </p>
            )}
          </TooltipContent>
        </Tooltip>
      </div>
    );
  }

  // 工程计算模式
  return (
    <div className="space-y-2">
      <div className="flex items-center justify-between">
        <span className="text-sm font-medium">工程计算模式</span>
        <div className="flex items-center gap-1">
          <Tooltip>
            <TooltipTrigger asChild>
              <Button
                type="button"
                variant="ghost"
                size="icon"
                onClick={clearCalculation}
                className="h-6 w-6"
                disabled={disabled}
              >
                <Trash2 className="w-3 h-3" />
              </Button>
            </TooltipTrigger>
            <TooltipContent>
              <p>清空计算参数</p>
            </TooltipContent>
          </Tooltip>
          <Tooltip>
            <TooltipTrigger asChild>
              <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={toggleMode}
                disabled={disabled}
                className="h-6 px-2"
              >
                <Calculator className="w-3 h-3 mr-1" />
                输入
              </Button>
            </TooltipTrigger>
            <TooltipContent>
              <p>切换回简单输入模式</p>
            </TooltipContent>
          </Tooltip>
        </div>
      </div>
      
      <div className="grid grid-cols-1 gap-3 p-3 border rounded-md bg-gray-50">
        {/* 工程参数选择 */}
        <div className="flex items-center gap-2">
          <Label className="text-xs w-20">工程参数:</Label>
          <select
            value={selectedParam}
            onChange={(e) => setSelectedParam(e.target.value)}
            className="flex-1 text-xs border rounded px-2 py-1 bg-white"
            disabled={disabled || paramsLoading}
          >
            <option value="">选择参数...</option>
            {paramsLoading && <option key="loading" disabled>加载中...</option>}
            {!paramsLoading && engineeringParams.length === 0 && (
              <option key="no-params" disabled>暂无工程参数</option>
            )}
            {!paramsLoading && engineeringParams.map((param, index) => (
              <option 
                key={`param-${param.num}-${index}`} 
                value={param.num}
              >
                {/* 修复：显示参数名称和数值 */}
                {param.name} (值: {getParamValue(param)})
              </option>
            ))}
          </select>
        </div>

        {/* 系数输入 */}
        <div className="flex items-center gap-2">
          <Label className="text-xs w-20">工程系数:</Label>
          <Input
            type="number"
            value={coefficient}
            onChange={(e) => setCoefficient(e.target.value)}
            min="0"
            step="0.1"
            className="flex-1 text-xs h-6"
            disabled={disabled || !selectedParam}
          />
        </div>

        {/* 备用数量 */}
        <div className="flex items-center gap-2">
          <Label className="text-xs w-20">预留量:</Label>
          <Input
            type="number"
            value={reserve}
            onChange={(e) => setReserve(e.target.value)}
            min="0"
            step="1"
            className="flex-1 text-xs h-6"
            disabled={disabled || !selectedParam}
          />
        </div>

        {/* 计算结果显示 */}
        <div className="flex items-center gap-2 p-2 bg-white rounded border">
          <Label className="text-xs font-medium">计算公式:</Label>
          <span className="flex-1 text-sm font-bold text-blue-600">
            {selectedParam ? (
              <>
                {paramValue} × {coefficient} + {reserve} = {finalValue}
              </>
            ) : (
              "请选择工程参数"
            )}
          </span>
        </div>

        {/* 当前值显示 */}
        <div className="flex items-center gap-2">
          <Label className="text-xs w-20">计算结果:</Label>
          <Input
            type="number"
            value={finalValue}
            readOnly
            className="flex-1 text-xs h-6 font-bold text-blue-600"
          />
        </div>
      </div>
    </div>
  );
};

// 措施编辑器组件
const MeasuresEditor = ({
  measures,
  measureType,
  title,
  icon: Icon,
  onChange,
  disabled,
}) => {
  const addMeasure = () => {
    onChange([...measures, ""]);
  };

  const updateMeasure = (measureIndex, value) => {
    const newMeasures = [...measures];
    newMeasures[measureIndex] = value;
    onChange(newMeasures);
  };

  const removeMeasure = (measureIndex) => {
    const newMeasures = measures.filter((_, i) => i !== measureIndex);
    onChange(newMeasures);
  };

  return (
    <div className="space-y-2">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <Icon className="w-4 h-4 text-blue-600" />
          <span className="font-medium">{title}</span>
        </div>
        <Button
          type="button"
          size="sm"
          variant="outline"
          onClick={addMeasure}
          disabled={disabled}
        >
          <Plus className="w-3 h-3 mr-1" />
          添加
        </Button>
      </div>
      <div className="space-y-2">
        {measures.map((measure, measureIndex) => (
          <div key={measureIndex} className="flex items-center gap-2">
            <Input
              value={measure}
              onChange={(e) => updateMeasure(measureIndex, e.target.value)}
              placeholder={`输入${title}...`}
              disabled={disabled}
            />
            <Button
              type="button"
              variant="ghost"
              size="icon"
              onClick={() => removeMeasure(measureIndex)}
              className="text-red-500 hover:text-red-700"
              disabled={disabled}
            >
              <Trash2 className="w-3 h-3" />
            </Button>
          </div>
        ))}
      </div>
    </div>
  );
};

// 资源编辑器组件
const ResourceEditor = ({
  resources,
  resourceType,
  title,
  icon: Icon,
  fields,
  onChange,
  disabled,
  minQuantity = 1,
  schemeId,
  engineeringParams = [],
  paramsLoading = false,
}) => {
  const addResource = () => {
    const newResource = fields.reduce((acc, field) => {
      let defaultValue = field.type === "number" ? minQuantity : "";
      acc[field.key] = defaultValue;
      return acc;
    }, {});
    onChange([...resources, newResource]);
  };

  const updateResource = (resourceIndex, field, value) => {
    const newResources = [...resources];
    
    let processedValue = value;
    
    // 修复：正确处理数量字段
    if (field === "quantity" || field.includes("quantity")) {
      const numValue = parseFloat(value) || 0;
      processedValue = Math.max(minQuantity, numValue);
    } else if (field.type === "number") {
      processedValue = parseFloat(value) || 0;
    }
    
    newResources[resourceIndex] = {
      ...newResources[resourceIndex],
      [field]: processedValue,
    };
    
    onChange(newResources);
  };

  const removeResource = (resourceIndex) => {
    const newResources = resources.filter((_, i) => i !== resourceIndex);
    onChange(newResources);
  };

  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <Icon className="w-4 h-4 text-blue-600" />
          <span className="font-medium">{title}</span>
          {(engineeringParams.length > 0 || paramsLoading) && (
            <Badge variant="outline" className="text-xs">
              {paramsLoading ? "加载中..." : `${engineeringParams.length}个参数可用`}
            </Badge>
          )}
        </div>
        <Button
          type="button"
          size="sm"
          variant="outline"
          onClick={addResource}
          disabled={disabled}
        >
          <Plus className="w-3 h-3 mr-1" />
          添加
        </Button>
      </div>
      
      {resources.length > 0 && (
        <div className="border rounded-md overflow-hidden">
          <Table>
            <TableHeader>
              <TableRow>
                {fields.map((field) => (
                  <TableHead key={field.key}>
                    {field.label}
                    {field.key.includes("quantity") && (
                      <span className="text-red-500 ml-1">*</span>
                    )}
                  </TableHead>
                ))}
                <TableHead>操作</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {resources.map((resource, resourceIndex) => (
                <TableRow key={resourceIndex}>
                  {fields.map((field) => (
                    <TableCell key={field.key}>
                      {field.key.includes("quantity") ? (
                        <EngineeringCalculator
                          value={resource[field.key] || minQuantity}
                          onChange={(value) => updateResource(resourceIndex, field.key, value)}
                          schemeId={schemeId}
                          disabled={disabled}
                          minQuantity={minQuantity}
                          engineeringParams={engineeringParams}
                          paramsLoading={paramsLoading}
                        />
                      ) : (
                        <Input
                          type={field.type || "text"}
                          value={resource[field.key] || ""}
                          onChange={(e) =>
                            updateResource(resourceIndex, field.key, e.target.value)
                          }
                          placeholder={field.placeholder}
                          className="min-w-0"
                          disabled={disabled}
                        />
                      )}
                    </TableCell>
                  ))}
                  <TableCell>
                    <Button
                      type="button"
                      variant="ghost"
                      size="icon"
                      onClick={() => removeResource(resourceIndex)}
                      className="text-red-500 hover:text-red-700"
                      disabled={disabled}
                    >
                      <Trash2 className="w-3 h-3" />
                    </Button>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      )}
      
      {resources.length === 0 && (
        <div className="text-center py-4 text-gray-500 border border-dashed rounded-md">
          <p className="text-sm">暂无{title}</p>
        </div>
      )}
    </div>
  );
};

// 可排序的步骤项组件
const SortableStepItem = ({
  id,
  step,
  index,
  onUpdateStepField,
  onUpdateStepResources,
  onRemove,
  availableStandards,
  availableRisks,
  allSteps,
  schemeId,
  engineeringParams = [],
  paramsLoading = false,
}) => {
  const [isExpanded, setIsExpanded] = useState(false);

  // 本地状态管理各种资源
  const [currentMaterials, setCurrentMaterials] = useState(step.requiredMaterials || []);
  const [currentPersonnel, setCurrentPersonnel] = useState(step.requiredPersonnel || []);
  const [currentEquipment, setCurrentEquipment] = useState(step.requiredEquipment || []);
  const [currentVehicles, setCurrentVehicles] = useState(step.requiredVehicles || []);
  const [currentTechnicalMeasures, setCurrentTechnicalMeasures] = useState(step.technicalMeasures || []);
  const [currentSafetyMeasures, setCurrentSafetyMeasures] = useState(step.safetyMeasures || []);
  const [currentQualityMeasures, setCurrentQualityMeasures] = useState(step.qualityMeasures || []);
  const [currentEnvironmentalMeasures, setCurrentEnvironmentalMeasures] = useState(step.environmentalMeasures || []);

  // 同步本地状态与props
  useEffect(() => {
    setCurrentMaterials(step.requiredMaterials || []);
    setCurrentPersonnel(step.requiredPersonnel || []);
    setCurrentEquipment(step.requiredEquipment || []);
    setCurrentVehicles(step.requiredVehicles || []);
    setCurrentTechnicalMeasures(step.technicalMeasures || []);
    setCurrentSafetyMeasures(step.safetyMeasures || []);
    setCurrentQualityMeasures(step.qualityMeasures || []);
    setCurrentEnvironmentalMeasures(step.environmentalMeasures || []);
  }, [
    step.requiredMaterials,
    step.requiredPersonnel,
    step.requiredEquipment,
    step.requiredVehicles,
    step.technicalMeasures,
    step.safetyMeasures,
    step.qualityMeasures,
    step.environmentalMeasures,
  ]);

  // 新步骤自动展开
  useEffect(() => {
    if (String(id).startsWith("new-")) {
      setIsExpanded(true);
    }
  }, [id]);

  const toggleExpansion = () => {
    setIsExpanded((prev) => !prev);
  };

  // 生成资源提示信息
  const generateResourceTooltip = (resources, type) => {
    if (!resources || resources.length === 0) return "无";
    return resources
      .map((resource) => {
        switch (type) {
          case "materials":
            return `${resource.name || "未知"} ${resource.specification || ""} ${resource.unit || ""} ${resource.quantity || 0}`;
          case "personnel":
            return `${resource.role || "未知"} ${resource.quantity || 0}人 (${resource.qualification || "无要求"})`;
          case "equipment":
            return `${resource.name || "未知"} ${resource.specification || ""} ${resource.unit || ""} ${resource.quantity || 0}`;
          case "vehicles":
            return `${resource.type || "未知"} ${resource.quantity || 0}辆 (${resource.licensePlate ? resource.licensePlate : "无车牌"})`;
          default:
            return "";
        }
      })
      .join("\n");
  };

  // 可用的前置步骤
  const availableStepsForPredecessor = useMemo(() => {
    return allSteps
      .filter((s, i) => i < index && s.stepOrder !== step.stepOrder)
      .sort((a, b) => a.stepOrder - b.stepOrder);
  }, [allSteps, index, step.stepOrder]);

  // 处理标签页保存
  const handleTabSave = useCallback(
    (resourceType, value) => {
      const validatedValue = value.map(item => {
        if (['requiredMaterials', 'requiredPersonnel', 'requiredEquipment', 'requiredVehicles'].includes(resourceType)) {
          return {
            ...item,
            quantity: Math.max(1, parseInt(item.quantity) || 1)
          };
        }
        return item;
      });
      
      onUpdateStepResources(index, resourceType, validatedValue);
    },
    [index, onUpdateStepResources]
  );

  return (
    <Draggable draggableId={String(id)} index={index}>
      {(provided, snapshot) => (
        <div
          ref={provided.innerRef}
          {...provided.draggableProps}
          className={`mb-4 ${snapshot.isDragging ? "transform rotate-2" : ""}`}
        >
          <Card className="rounded-lg overflow-hidden shadow-sm hover:shadow-md transition-shadow">
            <CardHeader
              className="flex flex-row items-center justify-between p-4 bg-gray-50 hover:bg-gray-100 cursor-pointer"
              onClick={toggleExpansion}
            >
              <div className="flex items-center gap-3">
                <div
                  {...provided.dragHandleProps}
                  className="cursor-grab text-gray-400 hover:text-gray-600"
                >
                  <GripVertical className="w-4 h-4" />
                </div>
                <div className="flex items-center gap-2">
                  {isExpanded ? (
                    <ChevronDown className="w-4 h-4" />
                  ) : (
                    <ChevronRight className="w-4 h-4" />
                  )}
                  <span className="font-bold text-blue-600">
                    #{step.stepOrder}
                  </span>
                  <span className="font-medium">
                    {step.stepName || "未命名步骤"}
                  </span>
                </div>
              </div>
              <div className="flex items-center gap-4">
                <div className="hidden md:flex items-center gap-4 text-sm text-gray-600">
                  <Tooltip>
                    <TooltipTrigger asChild>
                      <div className="flex items-center gap-1 cursor-help">
                        <Clock className="w-3 h-3" />
                        <span>{step.durationDays || 0}天</span>
                      </div>
                    </TooltipTrigger>
                    <TooltipContent>
                      <p>预计工期: {step.durationDays || 0} 天</p>
                    </TooltipContent>
                  </Tooltip>
                  <Tooltip>
                    <TooltipTrigger asChild>
                      <div className="flex items-center gap-1 cursor-help">
                        <Package className="w-3 h-3" />
                        <span>{(step.requiredMaterials || []).length}</span>
                      </div>
                    </TooltipTrigger>
                    <TooltipContent className="max-w-xs">
                      <p className="font-medium">
                        所需物料 ({(step.requiredMaterials || []).length}项):
                      </p>
                      <pre className="text-xs whitespace-pre-wrap mt-1">
                        {generateResourceTooltip(step.requiredMaterials, "materials")}
                      </pre>
                    </TooltipContent>
                  </Tooltip>
                  <Tooltip>
                    <TooltipTrigger asChild>
                      <div className="flex items-center gap-1 cursor-help">
                        <Users className="w-3 h-3" />
                        <span>{(step.requiredPersonnel || []).length}</span>
                      </div>
                    </TooltipTrigger>
                    <TooltipContent className="max-w-xs">
                      <p className="font-medium">
                        所需人员 ({(step.requiredPersonnel || []).length}项):
                      </p>
                      <pre className="text-xs whitespace-pre-wrap mt-1">
                        {generateResourceTooltip(step.requiredPersonnel, "personnel")}
                      </pre>
                    </TooltipContent>
                  </Tooltip>
                </div>
                <Button
                  type="button"
                  variant="ghost"
                  size="icon"
                  onClick={(e) => {
                    e.stopPropagation();
                    onRemove(index);
                  }}
                  className="text-red-500 hover:text-red-700"
                >
                  <Trash2 className="w-4 h-4" />
                </Button>
              </div>
            </CardHeader>

            {!isExpanded && (
              <CardContent className="p-4 pt-2">
                <div className="pl-8 pr-4 space-y-2">
                  {step.description && (
                    <p className="text-sm text-gray-600 line-clamp-2">
                      {step.description}
                    </p>
                  )}
                  {(step.predecessorSteps || []).length > 0 && (
                    <div className="flex items-center gap-2">
                      <Calendar className="w-3 h-3 text-gray-500" />
                      <span className="text-xs font-medium text-gray-600">
                        依赖:
                      </span>
                      <div className="flex flex-wrap gap-1">
                        {(step.predecessorSteps || []).map((p) => (
                          <Badge
                            key={p}
                            variant="secondary"
                            className="text-xs"
                          >
                            步骤 #{p}
                          </Badge>
                        ))}
                      </div>
                    </div>
                  )}
                </div>
              </CardContent>
            )}

            {isExpanded && (
              <CardContent className="border-t bg-gray-50 p-4">
                <div className="space-y-4">
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div>
                      <Label className="text-sm font-medium">步骤名称</Label>
                      <Input
                        value={step.stepName}
                        onChange={(e) =>
                          onUpdateStepField(index, "stepName", e.target.value)
                        }
                        placeholder="例如: 搭设跨越架"
                      />
                    </div>
                    <div>
                      <Label className="text-sm font-medium">工期 (天)</Label>
                      <Input
                        type="number"
                        min="0.1"
                        step="0.1"
                        value={step.durationDays}
                        onChange={(e) =>
                          onUpdateStepField(
                            index,
                            "durationDays",
                            parseFloat(e.target.value)
                          )
                        }
                        placeholder="1"
                      />
                    </div>
                  </div>

                  <div>
                    <Label className="block text-sm font-medium mb-2 flex items-center gap-1">
                      <Calendar className="w-4 h-4" />
                      前置步骤依赖
                    </Label>
                    {availableStepsForPredecessor.length > 0 ? (
                      <div className="grid grid-cols-2 md:grid-cols-3 gap-2 p-3 bg-gray-50 rounded-lg border">
                        {availableStepsForPredecessor.map((predStep) => {
                          const predStepNumber = predStep.stepOrder;
                          return (
                            <label
                              key={predStep.id || predStepNumber}
                              className="flex items-center space-x-2 cursor-pointer"
                            >
                              <input
                                type="checkbox"
                                checked={(step.predecessorSteps || []).some(
                                  (p) => String(p) === String(predStepNumber)
                                )}
                                onChange={(e) => {
                                  const currentPredecessors = (
                                    step.predecessorSteps || []
                                  ).map(String);
                                  const targetStep = String(predStepNumber);

                                  let newPredecessors;
                                  if (e.target.checked) {
                                    newPredecessors = [
                                      ...new Set([...currentPredecessors, targetStep]),
                                    ];
                                  } else {
                                    newPredecessors = currentPredecessors.filter(
                                      (p) => p !== targetStep
                                    );
                                  }

                                  onUpdateStepField(
                                    index,
                                    "predecessorSteps",
                                    newPredecessors.map(Number)
                                  );
                                }}
                                className="rounded border-gray-300"
                              />
                              <span className="text-sm">
                                步骤{predStepNumber}: {predStep.stepName}
                              </span>
                            </label>
                          );
                        })}
                      </div>
                    ) : (
                      <p className="text-sm text-gray-500 p-3 bg-gray-50 rounded-lg border">
                        无可选前置步骤（当前为第{step.stepOrder}个步骤）
                      </p>
                    )}
                  </div>

                  <div>
                    <Label className="text-sm font-medium">工作内容描述</Label>
                    <AutoResizingTextarea
                      value={step.description}
                      onChange={(e) =>
                        onUpdateStepField(index, "description", e.target.value)
                      }
                      placeholder="详细描述此步骤的工作内容和要求"
                      rows={3}
                      className="w-full px-3 py-2 border rounded-md"
                    />
                  </div>

                  <Tabs defaultValue="materials" className="w-full">
                    <TabsList className="grid w-full grid-cols-4 md:grid-cols-8">
                      <TabsTrigger value="materials">物料</TabsTrigger>
                      <TabsTrigger value="personnel">人员</TabsTrigger>
                      <TabsTrigger value="equipment">工器具</TabsTrigger>
                      <TabsTrigger value="vehicles">车辆</TabsTrigger>
                      <TabsTrigger value="technical">技术</TabsTrigger>
                      <TabsTrigger value="safety">安全</TabsTrigger>
                      <TabsTrigger value="quality">质量</TabsTrigger>
                      <TabsTrigger value="environmental">环保</TabsTrigger>
                    </TabsList>

                    {/* 物料标签页 */}
                    <TabsContent value="materials" className="mt-4">
                      <div className="mb-4 p-3 bg-blue-50 border border-blue-200 rounded-md">
                        <div className="flex items-center text-sm text-blue-700">
                          <Info className="w-4 h-4 mr-2" />
                          <span>工程计算模式已启用，修改参数将自动计算数量</span>
                        </div>
                      </div>
                      <ResourceEditor
                        resources={currentMaterials}
                        resourceType="requiredMaterials"
                        title="所需物料"
                        icon={Package}
                        fields={[
                          {
                            key: "name",
                            label: "名称",
                            placeholder: "物料名称",
                          },
                          {
                            key: "specification",
                            label: "规格",
                            placeholder: "规格型号",
                          },
                          { key: "unit", label: "单位", placeholder: "单位" },
                          {
                            key: "quantity",
                            label: "数量",
                            type: "number",
                            placeholder: "数量",
                          },
                        ]}
                        minQuantity={1}
                        schemeId={schemeId}
                        engineeringParams={engineeringParams}
                        paramsLoading={paramsLoading}
                        onChange={(newResources) => {
                          const validatedResources = newResources.map(item => ({
                            ...item,
                            quantity: Math.max(1, parseInt(item.quantity) || 1)
                          }));
                          setCurrentMaterials(validatedResources);
                          handleTabSave("requiredMaterials", validatedResources);
                        }}
                      />
                    </TabsContent>

                    {/* 人员标签页 */}
                    <TabsContent value="personnel" className="mt-4">
                      <div className="mb-4 p-3 bg-blue-50 border border-blue-200 rounded-md">
                        <div className="flex items-center text-sm text-blue-700">
                          <Info className="w-4 h-4 mr-2" />
                          <span>工程计算模式已启用，修改参数将自动计算数量</span>
                        </div>
                      </div>
                      <ResourceEditor
                        resources={currentPersonnel}
                        resourceType="requiredPersonnel"
                        title="所需人员"
                        icon={Users}
                        fields={[
                          {
                            key: "role",
                            label: "工种/岗位",
                            placeholder: "工种岗位",
                          },
                          {
                            key: "quantity",
                            label: "人数",
                            type: "number",
                            placeholder: "人数",
                          },
                          {
                            key: "qualification",
                            label: "资质要求",
                            placeholder: "资质要求",
                          },
                        ]}
                        minQuantity={1}
                        schemeId={schemeId}
                        engineeringParams={engineeringParams}
                        paramsLoading={paramsLoading}
                        onChange={(newResources) => {
                          const validatedResources = newResources.map(item => ({
                            ...item,
                            quantity: Math.max(1, parseInt(item.quantity) || 1)
                          }));
                          setCurrentPersonnel(validatedResources);
                          handleTabSave("requiredPersonnel", validatedResources);
                        }}
                      />
                    </TabsContent>

                    {/* 工器具标签页 */}
                    <TabsContent value="equipment" className="mt-4">
                      <div className="mb-4 p-3 bg-blue-50 border border-blue-200 rounded-md">
                        <div className="flex items-center text-sm text-blue-700">
                          <Info className="w-4 h-4 mr-2" />
                          <span>工程计算模式已启用，修改参数将自动计算数量</span>
                        </div>
                      </div>
                      <ResourceEditor
                        resources={currentEquipment}
                        resourceType="requiredEquipment"
                        title="所需工器具"
                        icon={Wrench}
                        fields={[
                          {
                            key: "name",
                            label: "名称",
                            placeholder: "工器具名称",
                          },
                          {
                            key: "specification",
                            label: "规格",
                            placeholder: "规格型号",
                          },
                          { key: "unit", label: "单位", placeholder: "单位" },
                          {
                            key: "quantity",
                            label: "数量",
                            type: "number",
                            placeholder: "数量",
                          },
                        ]}
                        minQuantity={1}
                        schemeId={schemeId}
                        engineeringParams={engineeringParams}
                        paramsLoading={paramsLoading}
                        onChange={(newResources) => {
                          const validatedResources = newResources.map(item => ({
                            ...item,
                            quantity: Math.max(1, parseInt(item.quantity) || 1)
                          }));
                          setCurrentEquipment(validatedResources);
                          handleTabSave("requiredEquipment", validatedResources);
                        }}
                      />
                    </TabsContent>

                    {/* 车辆标签页 */}
                    <TabsContent value="vehicles" className="mt-4">
                      <div className="mb-4 p-3 bg-blue-50 border border-blue-200 rounded-md">
                        <div className="flex items-center text-sm text-blue-700">
                          <Info className="w-4 h-4 mr-2" />
                          <span>工程计算模式已启用，修改参数将自动计算数量</span>
                        </div>
                      </div>
                      <ResourceEditor
                        resources={currentVehicles}
                        resourceType="requiredVehicles"
                        title="所需车辆"
                        icon={Truck}
                        fields={[
                          {
                            key: "type",
                            label: "类型",
                            placeholder: "车辆类型",
                          },
                          {
                            key: "licensePlate",
                            label: "车牌号",
                            placeholder: "可选",
                          },
                          {
                            key: "quantity",
                            label: "数量",
                            type: "number",
                            placeholder: "数量",
                          },
                        ]}
                        minQuantity={1}
                        schemeId={schemeId}
                        engineeringParams={engineeringParams}
                        paramsLoading={paramsLoading}
                        onChange={(newResources) => {
                          const validatedResources = newResources.map(item => ({
                            ...item,
                            quantity: Math.max(1, parseInt(item.quantity) || 1)
                          }));
                          setCurrentVehicles(validatedResources);
                          handleTabSave("requiredVehicles", validatedResources);
                        }}
                      />
                    </TabsContent>

                    {/* 技术措施标签页 */}
                    <TabsContent value="technical" className="mt-4">
                      <MeasuresEditor
                        measures={currentTechnicalMeasures}
                        measureType="technicalMeasures"
                        title="技术措施"
                        icon={Wrench}
                        onChange={(newMeasures) => {
                          setCurrentTechnicalMeasures(newMeasures);
                          handleTabSave("technicalMeasures", newMeasures);
                        }}
                      />
                    </TabsContent>

                    {/* 安全措施标签页 */}
                    <TabsContent value="safety" className="mt-4">
                      <MeasuresEditor
                        measures={currentSafetyMeasures}
                        measureType="safetyMeasures"
                        title="安全措施"
                        icon={Shield}
                        onChange={(newMeasures) => {
                          setCurrentSafetyMeasures(newMeasures);
                          handleTabSave("safetyMeasures", newMeasures);
                        }}
                      />
                    </TabsContent>

                    {/* 质量措施标签页 */}
                    <TabsContent value="quality" className="mt-4">
                      <MeasuresEditor
                        measures={currentQualityMeasures}
                        measureType="qualityMeasures"
                        title="质量措施"
                        icon={CheckSquare}
                        onChange={(newMeasures) => {
                          setCurrentQualityMeasures(newMeasures);
                          handleTabSave("qualityMeasures", newMeasures);
                        }}
                      />
                    </TabsContent>

                    {/* 环保措施标签页 */}
                    <TabsContent value="environmental" className="mt-4">
                      <MeasuresEditor
                        measures={currentEnvironmentalMeasures}
                        measureType="environmentalMeasures"
                        title="环保措施"
                        icon={Leaf}
                        onChange={(newMeasures) => {
                          setCurrentEnvironmentalMeasures(newMeasures);
                          handleTabSave("environmentalMeasures", newMeasures);
                        }}
                      />
                    </TabsContent>
                  </Tabs>
                </div>
              </CardContent>
            )}
          </Card>
        </div>
      )}
    </Draggable>
  );
};

// 主组件
function StepsManager({
  scheme,
  onUpdate,
  availableStandards,
  availableRisks,
}) {
  const [editedSteps, setEditedSteps] = useState([]);
  const [showGantt, setShowGantt] = useState(false);
  const [engineeringParams, setEngineeringParams] = useState([]);
  const [paramsLoading, setParamsLoading] = useState(false);

  // 从浏览器地址获取schemeId
  const schemeId = useMemo(() => {
    // 方法1: 从URL查询参数获取
    const urlParams = new URLSearchParams(window.location.search);
    let idFromUrl = urlParams.get('schemeId');
    
    // 方法2: 从URL路径中提取
    if (!idFromUrl) {
      const pathSegments = window.location.pathname.split('/');
      const schemeIndex = pathSegments.indexOf('scheme');
      if (schemeIndex !== -1 && pathSegments[schemeIndex + 1]) {
        idFromUrl = pathSegments[schemeIndex + 1];
      }
    }
    
    // 方法3: 使用props中的scheme.id作为备选
    return idFromUrl || scheme?.id || '';
  }, [scheme?.id]);

  // 修复：改进工程参数加载逻辑，适配新的API响应格式
  useEffect(() => {
    const loadEngineeringParams = async () => {
      if (!schemeId) {
        console.warn("没有找到schemeId，无法加载工程参数");
        return;
      }

      setParamsLoading(true);
      try {
        console.log("正在加载工程参数，schemeId:", schemeId);
        const response = await ConstructionSchemeAPI.getLengthList(schemeId);
        console.log("工程参数API响应:", response);
        
        let params = [];
        
        // 修复：处理不同的响应格式
        if (response && response.data) {
          params = Array.isArray(response.data) ? response.data : [];
        } else if (Array.isArray(response)) {
          params = response;
        }
        
        // 修复：适配新的API响应格式，使用 num 字段作为值
        const processedParams = params.map((param, index) => ({
          num: param.num !== null && param.num !== undefined ? param.num : index + 1,
          name: param.name || `参数${index + 1}`,
          // 使用 num 字段作为值，如果 num 为 null 则使用 0
          value: param.num !== null && param.num !== undefined ? parseFloat(param.num) || 0 : 0,
          // 保留原始数据以备其他用途
          ...param
        }));
        
        setEngineeringParams(processedParams);
        console.log("处理后的工程参数:", processedParams);
      } catch (error) {
        console.error("加载工程参数失败:", error);
        setEngineeringParams([]);
      } finally {
        setParamsLoading(false);
      }
    };

    // 只在schemeId存在时加载
    if (schemeId) {
      loadEngineeringParams();
    }
  }, [schemeId]);

  // 类别映射
  const categoryMapping = useMemo(
    () => ({
      基础工程: "foundations",
      杆塔组立: "towerAssembly",
      架线工程: "stringingWorks",
      带电作业: "liveLineWork",
      运输作业: "transportation",
      环境作业: "environmental",
      管理作业: "management",
    }),
    []
  );

  // 加载数据
  useEffect(() => {
    const stepsData = scheme.constructionSteps || [];
    const completeSteps = stepsData.map((step) => {
      const cleanPredecessors = step.predecessorSteps
        ? [...new Set(step.predecessorSteps.map(String))].map(Number)
        : [];
      
      return {
        id: step.id || `step-${step.stepOrder}-${Date.now()}`,
        stepOrder: step.stepOrder || 1,
        stepName: step.stepName || "",
        description: step.description || "",
        durationDays: step.durationDays || 1,
        personnelCount: step.personnelCount || 0,
        predecessorSteps: cleanPredecessors,
        technicalMeasures: Array.isArray(step.technicalMeasures)
          ? [...step.technicalMeasures]
          : [],
        safetyMeasures: Array.isArray(step.safetyMeasures)
          ? [...step.safetyMeasures]
          : [],
        qualityMeasures: Array.isArray(step.qualityMeasures)
          ? [...step.qualityMeasures]
          : [],
        environmentalMeasures: Array.isArray(step.environmentalMeasures)
          ? [...step.environmentalMeasures]
          : [],
        requiredMaterials: Array.isArray(step.requiredMaterials)
          ? JSON.parse(JSON.stringify(step.requiredMaterials)).map(item => ({
              ...item,
              quantity: Math.max(1, parseInt(item.quantity) || 1)
            }))
          : [],
        requiredPersonnel: Array.isArray(step.requiredPersonnel)
          ? JSON.parse(JSON.stringify(step.requiredPersonnel)).map(item => ({
              ...item,
              quantity: Math.max(1, parseInt(item.quantity) || 1)
            }))
          : [],
        requiredEquipment: Array.isArray(step.requiredEquipment)
          ? JSON.parse(JSON.stringify(step.requiredEquipment)).map(item => ({
              ...item,
              quantity: Math.max(1, parseInt(item.quantity) || 1)
            }))
          : [],
        requiredVehicles: Array.isArray(step.requiredVehicles)
          ? JSON.parse(JSON.stringify(step.requiredVehicles)).map(item => ({
              ...item,
              quantity: Math.max(1, parseInt(item.quantity) || 1)
            }))
          : [],
        standardWorkCategories: Array.isArray(step.standardWorkCategories)
          ? [...step.standardWorkCategories]
          : [],
        associatedRiskCodes: Array.isArray(step.associatedRiskCodes)
          ? [...step.associatedRiskCodes]
          : [],
      };
    });

    setEditedSteps(completeSteps);
  }, [scheme.constructionSteps]);

  // 重新计算措施
  const recalculateMeasures = useCallback(
    (currentSteps, currentSchemeSafetyMeasures) => {
      const allPossibleMeasuresFromKB = new Set(
        (availableRisks || []).flatMap((r) => r.controlMeasures || [])
      );

      const manualMeasures = (currentSchemeSafetyMeasures || []).filter(
        (m) => !allPossibleMeasuresFromKB.has(m)
      );

      const allSelectedRiskCodes = new Set(
        currentSteps.flatMap((step) => step.associatedRiskCodes || [])
      );

      const newGeneratedMeasures = new Set();
      allSelectedRiskCodes.forEach((code) => {
        const riskPoint = (availableRisks || []).find(
          (r) => r.riskCode === code
        );
        if (riskPoint && riskPoint.controlMeasures) {
          riskPoint.controlMeasures.forEach((measure) =>
            newGeneratedMeasures.add(measure)
          );
        }
      });

      const finalMeasures = [
        ...new Set([...manualMeasures, ...Array.from(newGeneratedMeasures)]),
      ];

      onUpdate({
        ...scheme,
        constructionSteps: currentSteps,
        schemeLevelSafetyMeasures: finalMeasures,
      });
    },
    [availableRisks, onUpdate, scheme]
  );

  // 拖拽结束处理
  const handleDragEnd = (result) => {
    if (!result.destination) {
      return;
    }

    const newSteps = Array.from(editedSteps);
    const [removed] = newSteps.splice(result.source.index, 1);
    newSteps.splice(result.destination.index, 0, removed);

    // 重新计算步骤序号
    const reorderedSteps = newSteps.map((step, index) => ({
      ...step,
      stepOrder: index + 1,
    }));

    setEditedSteps(reorderedSteps);
    onUpdate({ ...scheme, constructionSteps: reorderedSteps });
  };

  // 更新步骤字段
  const handleUpdateStepField = (indexToUpdate, field, value) => {
    let newSteps = editedSteps.map((step, idx) => {
      if (idx === indexToUpdate) {
        if (field === "predecessorSteps") {
          const uniqueValues = [...new Set(value.map(String))].map(Number);
          return { ...step, [field]: uniqueValues };
        }
        return { ...step, [field]: value };
      }
      return step;
    });

    // 如果更新的是标准作业类别，则自动关联风险点
    if (field === "standardWorkCategories") {
      const mappedCategories = value
        .map((category) => categoryMapping[category])
        .filter(Boolean);

      let relatedRiskCodes = [];
      if (mappedCategories.length > 0 && availableRisks) {
        relatedRiskCodes = availableRisks
          .filter(
            (risk) =>
              risk &&
              risk.primaryCategory &&
              mappedCategories.includes(risk.primaryCategory)
          )
          .map((risk) => risk.riskCode);
      }

      const currentStep = newSteps[indexToUpdate];
      const updatedRiskCodes = [...new Set(relatedRiskCodes)];
      newSteps[indexToUpdate] = {
        ...currentStep,
        associatedRiskCodes: updatedRiskCodes,
      };

      recalculateMeasures(newSteps, scheme.schemeLevelSafetyMeasures);
    }

    setEditedSteps(newSteps);
    onUpdate({ ...scheme, constructionSteps: newSteps });
  };

  // 更新步骤资源
  const handleUpdateStepResources = (
    indexToUpdate,
    resourceType,
    resources
  ) => {
    const newSteps = editedSteps.map((step, idx) =>
      idx === indexToUpdate ? { ...step, [resourceType]: resources } : step
    );

    setEditedSteps(newSteps);
    onUpdate({ ...scheme, constructionSteps: newSteps });
  };

  // 添加步骤
  const handleAddStep = () => {
    const newStep = {
      id: `new-${Date.now()}`,
      stepOrder: editedSteps.length + 1,
      stepName: "新步骤",
      description: "",
      durationDays: 1,
      personnelCount: 0,
      predecessorSteps: [],
      requiredMaterials: [],
      requiredPersonnel: [],
      requiredEquipment: [],
      requiredVehicles: [],
      technicalMeasures: [],
      safetyMeasures: [],
      qualityMeasures: [],
      environmentalMeasures: [],
      standardWorkCategories: [],
      associatedRiskCodes: [],
    };

    const newSteps = [...editedSteps, newStep];
    setEditedSteps(newSteps);
    onUpdate({ ...scheme, constructionSteps: newSteps });
  };

  // 删除步骤
  const handleRemoveStep = (indexToRemove) => {
    const stepToRemove = editedSteps[indexToRemove];
    const removedStepOrder = stepToRemove.stepOrder;

    const newSteps = editedSteps
      .filter((_, index) => index !== indexToRemove)
      .map((step, index) => {
        const cleanedPredecessors = step.predecessorSteps
          ? step.predecessorSteps.filter((order) => order !== removedStepOrder)
          : [];

        return {
          ...step,
          stepOrder: index + 1,
          predecessorSteps: cleanedPredecessors,
        };
      });

    setEditedSteps(newSteps);
    recalculateMeasures(newSteps, scheme.schemeLevelSafetyMeasures);
  };

  // 甘特图数据
  const ganttData = useMemo(() => {
    const calculateSchedule = (steps) => {
      if (!steps || !steps.length) return [];

      let schedule = steps.map((s) => ({
        ...s,
        durationDays: s.durationDays || 1,
        startDay: 0,
        endDay: 0,
        visited: false,
        inStack: false,
      }));

      // 检测循环依赖
      const hasCycle = (step, schedule) => {
        if (step.inStack) return true;
        if (step.visited) return false;

        step.visited = true;
        step.inStack = true;

        const predecessors = step.predecessorSteps || [];
        for (const predOrder of predecessors) {
          const predStep = schedule.find((s) => s.stepOrder === predOrder);
          if (predStep && hasCycle(predStep, schedule)) {
            return true;
          }
        }

        step.inStack = false;
        return false;
      };

      // 检查是否有循环依赖
      let cycleDetected = false;
      for (const step of schedule) {
        if (hasCycle(step, schedule)) {
          cycleDetected = true;
          console.error(`检测到循环依赖，涉及步骤: ${step.stepOrder}`);
          break;
        }
      }

      if (cycleDetected) {
        schedule = schedule.map((step) => ({
          ...step,
          predecessorSteps: [],
          startDay: 0,
          endDay: 0,
        }));
      }

      let scheduledCount = 0;
      let iterations = 0;
      const maxIterations = schedule.length * 2;

      while (scheduledCount < schedule.length && iterations < maxIterations) {
        let newScheduledInLoop = false;

        for (const step of schedule) {
          if (step.startDay > 0) continue;

          const predecessors = step.predecessorSteps || [];
          let dependenciesMet = true;
          let maxPredecessorEndDay = 0;

          for (const predOrder of predecessors) {
            const predStep = schedule.find((s) => s.stepOrder === predOrder);
            if (!predStep) {
              dependenciesMet = false;
              console.warn(
                `步骤 ${step.stepOrder} 依赖了不存在的步骤 ${predOrder}`
              );
              break;
            }

            if (predStep.startDay === 0) {
              dependenciesMet = false;
              break;
            }

            maxPredecessorEndDay = Math.max(
              maxPredecessorEndDay,
              predStep.endDay
            );
          }

          if (dependenciesMet) {
            step.startDay = maxPredecessorEndDay + 1;
            if (predecessors.length === 0) {
              step.startDay = 1;
            }
            step.endDay = step.startDay + step.durationDays - 1;
            scheduledCount++;
            newScheduledInLoop = true;
          }
        }

        if (!newScheduledInLoop) {
          const unscheduledSteps = schedule.filter((s) => s.startDay === 0);
          console.error(
            `无法安排所有步骤，${unscheduledSteps.length}个步骤未安排，可能存在依赖问题。`
          );

          unscheduledSteps.forEach((step, idx) => {
            const lastEndDay = Math.max(...schedule.map((s) => s.endDay), 0);
            step.startDay = lastEndDay + 1;
            step.endDay = step.startDay + step.durationDays - 1;
            scheduledCount++;
          });

          break;
        }

        iterations++;
      }

      schedule.sort(
        (a, b) => a.startDay - b.startDay || a.stepOrder - b.stepOrder
      );
      return schedule;
    };

    const scheduledSteps = calculateSchedule(editedSteps);

    return scheduledSteps.map((step) => ({
      name: `${step.stepOrder}. ${step.stepName}`,
      start: step.startDay > 1 ? step.startDay - 1 : 0,
      duration: step.durationDays,
      startDay: step.startDay,
      endDay: step.endDay,
    }));
  }, [editedSteps]);

  // 自定义工具提示
  const CustomTooltip = ({ active, payload, label }) => {
    if (active && payload && payload.length && payload[0].payload) {
      const data = payload[0].payload;
      return (
        <div className="bg-white p-3 border rounded shadow-lg text-sm">
          <p className="font-bold mb-1">{data.name || "未知步骤"}</p>
          <p>开始: 第 {data.startDay || 0} 天</p>
          <p>结束: 第 {data.endDay || 0} 天</p>
          <p>工期: {data.duration || 0} 天</p>
        </div>
      );
    }
    return null;
  };

  // 自定义条形图标签
  const CustomBarLabel = ({ x, y, width, height, value, payload }) => {
    if (!payload || !payload.name || width < 60) return null;

    const name = payload.name.split(". ").slice(1).join(". ");
    const displayName = name.length > 20 ? `${name.substring(0, 18)}...` : name;

    return (
      <text
        x={x + 10}
        y={y + height / 2}
        fill="#fff"
        textAnchor="start"
        dominantBaseline="middle"
        fontSize={11}
        fontWeight="500"
      >
        {`${displayName} (${value}天)`}
      </text>
    );
  };

  // 计算总人力和总工期
  const totalManpowerDays = useMemo(() => {
    return editedSteps.reduce(
      (sum, step) => sum + (step.durationDays || 0) * (step.personnelCount || 0),
      0
    );
  }, [editedSteps]);

  const totalDurationGantt = useMemo(() => {
    return Math.max(...ganttData.map((d) => d.endDay), 0);
  }, [ganttData]);

  return (
    <TooltipProvider>
      <Card>
        <CardHeader className="flex flex-row items-center justify-between">
          <CardTitle>施工步骤管理</CardTitle>
          <div className="flex items-center gap-2">
            {paramsLoading && (
              <Badge variant="secondary" className="ml-2">
                加载工程参数中...
              </Badge>
            )}
            {engineeringParams.length > 0 && (
              <Badge variant="outline" className="ml-2">
                已加载{engineeringParams.length}个工程参数
              </Badge>
            )}
            <div className="flex items-center border rounded-lg p-1">
              <Button
                variant={!showGantt ? "default" : "ghost"}
                size="sm"
                onClick={() => setShowGantt(false)}
                className="h-8"
              >
                <Edit3 className="w-4 h-4 mr-1" />
                步骤详情
              </Button>
              <Button
                variant={showGantt ? "default" : "ghost"}
                size="sm"
                onClick={() => setShowGantt(true)}
                className="h-8"
              >
                <BarChart3 className="w-4 h-4 mr-1" />
                进度甘特图
              </Button>
            </div>
            <Button onClick={handleAddStep} variant="outline">
              <Plus className="w-4 h-4 mr-2" />
              添加步骤
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          {!showGantt ? (
            editedSteps.length === 0 ? (
              <div className="text-center py-8 text-gray-500 border border-dashed rounded-lg">
                <p>暂无施工步骤</p>
                <Button
                  onClick={handleAddStep}
                  variant="outline"
                  className="mt-2"
                >
                  <Plus className="w-4 h-4 mr-2" />
                  添加第一个步骤
                </Button>
                {schemeId && (
                  <div className="mt-4 text-xs text-gray-400">
                    方案ID: {schemeId} | 
                    工程参数: {engineeringParams.length}个
                  </div>
                )}
              </div>
            ) : (
              <DragDropContext onDragEnd={handleDragEnd}>
                <Droppable droppableId="steps">
                  {(provided) => (
                    <div {...provided.droppableProps} ref={provided.innerRef}>
                      {editedSteps.map((step, index) => (
                        <SortableStepItem
                          key={step.id || step.stepOrder}
                          id={step.id || step.stepOrder}
                          step={step}
                          index={index}
                          onUpdateStepField={handleUpdateStepField}
                          onUpdateStepResources={handleUpdateStepResources}
                          onRemove={handleRemoveStep}
                          availableStandards={availableStandards}
                          availableRisks={availableRisks}
                          allSteps={editedSteps}
                          schemeId={schemeId}
                          engineeringParams={engineeringParams}
                          paramsLoading={paramsLoading}
                        />
                      ))}
                      {provided.placeholder}
                    </div>
                  )}
                </Droppable>
              </DragDropContext>
            )
          ) : (
            <div className="space-y-4">
              <div className="h-[600px] w-full bg-gray-50/50 p-4 rounded-lg border">
                {editedSteps.length > 0 ? (
                  <div className="text-center py-8">
                    <BarChart3 className="w-16 h-16 mx-auto mb-4 text-gray-300" />
                    <p>甘特图功能开发中...</p>
                  </div>
                ) : (
                  <div className="text-center py-8 text-gray-500 border border-dashed rounded-lg flex flex-col items-center justify-center h-full">
                    <BarChart3 className="w-16 h-16 text-gray-300 mb-4" />
                    <p>请添加施工步骤以显示甘特图。</p>
                  </div>
                )}
              </div>
              <div className="flex flex-col md:flex-row gap-2 md:gap-4 text-sm text-gray-600">
                <Badge variant="outline" className="text-xs">
                  总工期估算: {totalDurationGantt} 天
                </Badge>
                <Badge variant="outline" className="text-xs">
                  总人力: {totalManpowerDays} 人·天
                </Badge>
              </div>
            </div>
          )}
        </CardContent>
      </Card>
    </TooltipProvider>
  );
}

export default StepsManager;